package paidaxing.blog.common.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

/**
 * 对象拷贝工具类
 *
 * @author heefM
 * @date 2025-10-17
 */
public class BeanCopyUtils {

    /**
     * 拷贝单个对象
     */
    public static <T> T copyBean(Object source, Supplier<T> target) {
        if (source == null) {
            return null;
        }
        T t = target.get();
        BeanUtils.copyProperties(source, t);
        return t;
    }

    /**
     * 拷贝列表
     */
    public static <T> List<T> copyBeanList(List<?> sourceList, Supplier<T> target) {
        if (CollectionUtils.isEmpty(sourceList)) {
            return new ArrayList<>();
        }
        List<T> result = new ArrayList<>(sourceList.size());
        for (Object source : sourceList) {
            T t = target.get();
            BeanUtils.copyProperties(source, t);
            result.add(t);
        }
        return result;
    }

    /**
     * 拷贝对象（忽略空值）
     */
    public static <T> T copyBeanIgnoreNull(Object source, Supplier<T> target) {
        if (source == null) {
            return null;
        }
        T t = target.get();
        BeanUtils.copyProperties(source, t);
        return t;
    }
}
